import os
from fastapi import FastAPI
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from . import settings
from .apps.common.views import app as common_app
from .utils import middleware, exceptions
from fastapi.middleware.cors import CORSMiddleware


def create_app() -> FastAPI:
	# 读取环境配置文件
	load_dotenv()
	# 工厂函数，创建web应用对象
	app: FastAPI = FastAPI(
		title = os.environ.get('APP_NAME'),
		summary = os.environ.get('APP_SUMMARY'),
		description = os.environ.get('APP_DESCRIPTION'),
		version = os.environ.get('APP_VERSION'),
		# 注册异常处理函数
		exception_handlers = {
			exceptions.HTTPException: exceptions.global_http_exception_handler,
			exceptions.RequestValidationError: exceptions.global_request_exception_handler,
		},
	)

	# 把Tortoise-orm注册到App应用对象中
	register_tortoise(
		app,
		config = settings.TORTOISE_ORM,
		generate_schemas = False,  # 是否自动生成表结构
		add_exception_handlers = True,  # 是否启用自动异常处理
	)

	# 注册各个应用分组下的路由信息，合并到App应用对象
	app.include_router(common_app, prefix = '')

	# 注册中间件
	http_middlewares = app.middleware('http')
	http_middlewares(middleware.log_requests)

	origins = ['*']
	app.add_middleware(
		CORSMiddleware,
		allow_origins = origins,
		allow_credentials = True,
		allow_methods = ["GET", "POST", "DELETE"],
		allow_headers = ["Content-Type", "Authorization"]
	)

	return app
